﻿using System;
using System.Text;
using System.Net;
using System.IO;
using System.IO.Compression;

using Newtonsoft.Json.Linq;

namespace HttpUtility
{
    public class Poster
    {
        //public static CookieContainer cookie = new CookieContainer();
        /// <summary>
        /// 模拟Post请求，并获取JSON格式的结果
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public static JObject Post(string url, string postData)
        {
            try
            {
                string result = DoPost(url, postData);
                if (string.IsNullOrEmpty(result))
                    return null;
                else
                {
                    return JObject.Parse(result);
                }
            }
            catch { return null; }
        }

        /// <summary>
        /// 模拟网页Post请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public static string DoPost(string url, string postData)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                //request.CookieContainer = cookie;
                request.Method = "POST";
                request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
                request.KeepAlive = true;
                request.ContentType = "application/x-www-form-urlencoded";
                request.UserAgent = "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36";
                //request.ContentLength = Encoding.UTF8.GetByteCount(postData);
                //request.AllowWriteStreamBuffering = false;

                request.Headers.Set("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
                request.Headers.Set("Accept-Encoding", "gzip,deflate");
                //request.Headers[HttpRequestHeader.CacheControl] = "max-age=0";

                Stream myRequestStream = request.GetRequestStream();
                StreamWriter myStreamWriter = new StreamWriter(myRequestStream);
                myStreamWriter.Write(postData);
                myStreamWriter.Close();

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                //response.Cookies = cookie.GetCookies(response.ResponseUri);

                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = null;
                if (response.ContentEncoding.ToLower() == "gzip")
                {
                    myStreamReader = new System.IO.StreamReader(new GZipStream(myResponseStream, CompressionMode.Decompress), Encoding.GetEncoding("utf-8"));
                }
                else
                {
                    myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                }
                string retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();

                return retString;
            }
            catch (Exception ex)
            {
                return null;
                //return null;
            }
            finally
            {
                GC.Collect();
            }
        }

        /// <summary>
        /// 模拟GET请求，并返回JSON格式结果
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static JObject Get(string url)
        {
            return Get(url, "");
        }

        /// <summary>
        /// 模拟GET请求，并返回JSON格式结果
        /// </summary>
        /// <param name="url"></param>
        /// <param name="dataStr"></param>
        /// <returns></returns>
        public static JObject Get(string url, string dataStr)
        {
            try
            {
                string result = DoGet(url, dataStr);
                if (string.IsNullOrEmpty(result))
                    return null;
                else
                {
                    return JObject.Parse(result);
                }
            }
            catch { return null; }
        }

        /// <summary>
        /// 模拟GET请求，并返String格式结果
        /// </summary>
        /// <param name="Url"></param>
        /// <returns></returns>
        public static string DoGet(string Url)
        {
            return DoGet(Url, "");
        }

        /// <summary>
        /// 模拟Get请求，并返String格式结果
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="postDataStr"></param>
        /// <returns></returns>
        public static string DoGet(string Url, string dataStr)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (dataStr == "" ? "" : (Url.Contains("?") ? "" : "?")) + dataStr);
                request.Method = "GET";
                request.ContentType = "text/html;charset=UTF-8";

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                string retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();

                return retString;
            }
            catch
            {
                return "";
            }
            finally
            {
                GC.Collect();
            }
        }
    }
}
